/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.sales.ActivityManage;
import com.ybkj.daijia.server.sales.ActivityManage.ServiceType;
import com.ybkj.daijia.server.service.ActivityManageService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author Shine
 */
@Service
public class DefaultActivityManageService implements ActivityManageService {


    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private SalesApi salesApi;


    /* (non-Javadoc)
     * @see com.ybkj.shop.service.AdminService#queryAll()
     */
    @Override
    public Page<ActivityManage> findAll() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder sb = new StringBuilder();
        sb.append(salesApi.getCouponRuleBaseURL() + SalesApi.QUERY_ACTIVITYMANAGE
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", (Pager.getPage() + 1) + "");
        kv.put("rows", Pager.getLimit() + "");
        if (!principal.isCompanyType()) {
            kv.put("companyIds", String.valueOf(principal.getCompanyId()));
            sb.append("&companyIds={companyIds}");
        }

        String result = salesApi.get(sb.toString(), kv, settingUtils.get());
        List<ActivityManage> content = new ArrayList<ActivityManage>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content = gson.fromJson(ja.toString(), new TypeToken<List<ActivityManage>>() {
                }.getType());
            }
        }
        return new PageImpl<ActivityManage>(content, pageable, total);
    }

    @Override
    public Result<ActivityManage> create(ActivityManage activityManage) {

        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        if (activityManage.getCentreActivityImage() != null) {
            kv.add("centreActivityImage", activityManage.getCentreActivityImage());
        }
        if (activityManage.getBusinessActivityImage() != null) {
            kv.add("businessActivityImage", activityManage.getBusinessActivityImage());
        }
        if (null != activityManage.getChainedAddress()) {
            kv.add("chainedAddress", activityManage.getChainedAddress());
        }
        if (null != activityManage.getServiceType()) {
            kv.add("serviceType", activityManage.getServiceType().toString());
        }
        if (null != activityManage.getSort()) {
            kv.add("sort", String.valueOf(activityManage.getSort()));
        }
        if (null != activityManage.getShowLocation()) {
            kv.add("showLocation", activityManage.getShowLocation().toString());
        }
        kv.add("start", activityManage.getStart().toString());

        if (null != activityManage.getEnd()) {
            kv.add("end", activityManage.getEnd().toString());
        }
        kv.add("companyIds", "," + activityManage.getCompanyIds() + ",");

        kv.add("companyName", activityManage.getCompanyName());

        kv.add("companyId", principal.getCompanyId().toString());

        String resultStr = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.CREATE_ACTIVITYMANAGE, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }

        return result;
    }

    @Override
    public ActivityManage findOne(Long id) {
        Result<ActivityManage> result = salesApi.findOneActivityManage(id);

        return result.getResult();

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<ActivityManage> delete(Long id) {

        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        StringBuilder builder = new StringBuilder();

        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.DELETE_ACTIVITYMANAGE
            + "?id={id}&appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", id.toString());
        String resultStr = salesApi.delete(builder.toString(), kv, settingUtils.get());

        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
        } else {
            result.setSuccess(true);
        }

        return result;

    }

    @Transactional(rollbackFor = Exception.class)
    public Result<ActivityManage> update(ActivityManage activityManage) {
        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("id", activityManage.getId().toString());
        if (StringUtils.isNotBlank(activityManage.getChainedAddress())) {
            kv.add("chainedAddress", activityManage.getChainedAddress());
        }

        kv.add("serviceType", activityManage.getServiceType().toString());

        kv.add("sort", activityManage.getSort().toString());

        kv.add("showLocation", activityManage.getShowLocation().toString());
        if (StringUtils.isNotBlank(activityManage.getCentreActivityImage())) {
            kv.add("centreActivityImage", activityManage.getCentreActivityImage());
        }
        if (StringUtils.isNotBlank(activityManage.getBusinessActivityImage())) {
            kv.add("businessActivityImage", activityManage.getBusinessActivityImage());
        }

        if (null != activityManage.getEnd()) {
            kv.add("end", activityManage.getEnd().toString());
        }
        kv.add("companyIds", "," + activityManage.getCompanyIds() + ",");

        kv.add("companyName", activityManage.getCompanyName());
        String resultStr = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.UPDATE_ACTIVITYMANAGE, kv,
                settingUtils.get());

        JSONObject jo = new JSONObject(resultStr);
        Integer code = jo.getInt("code");
        if (code == 0) {
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }

        return result;
    }

    @Override
    public Page<ActivityManage> queryByCompany(Long companyId, Integer page, Integer limit) {
        Pageable pageable = new PageRequest(page, limit);
        StringBuilder sb = new StringBuilder();
        sb.append(salesApi.getCouponRuleBaseURL() + SalesApi.QUERY_BYCOMPANYID
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page));
        sb.append("&page={page}");
        kv.put("rows", String.valueOf(limit));
        sb.append("&rows={rows}");
        kv.put("companyId", String.valueOf(companyId));
        sb.append("&companyId={companyId}");
        String result = salesApi.get(sb.toString(), kv, settingUtils.get());
        List<ActivityManage> content = new ArrayList<ActivityManage>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content = gson.fromJson(ja.toString(), new TypeToken<List<ActivityManage>>() {
                }.getType());

            }
        }
        return new PageImpl<ActivityManage>(content, pageable, total);

    }

    @Override
    public List<ActivityManage> queryIndex(Long companyId, ServiceType serviceType) {
        StringBuilder sb = new StringBuilder();
        sb.append(salesApi.getCouponRuleBaseURL() + SalesApi.QUERY_BYCOMPANYID
            + "?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("companyId", String.valueOf(companyId));
        sb.append("&companyId={companyId}");
        kv.put("serviceType", String.valueOf(serviceType));
        sb.append("&serviceType={serviceType}");

        String result = salesApi.get(sb.toString(), kv, settingUtils.get());
        List<ActivityManage> content = new ArrayList<ActivityManage>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content = gson.fromJson(ja.toString(), new TypeToken<List<ActivityManage>>() {
                }.getType());
            }
        }

        return content;

    }

}
